/**
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import dataPreferences from '@ohos.data.preferences';
import promptAction from '@ohos.promptAction';
import StateModel from './StateModel';

let context = getContext(this);
let preference: dataPreferences.Preferences;
let preferenceTemp: dataPreferences.Preferences;

/**
 * Preference model.
 *
 * @param fruitData Fruit data.
 */
class PreferenceModel {
  /**
   * Read the specified Preferences persistence file and load the data into the Preferences instance.
   */
  async getPreferencesFromStorage(db_name: string) {
    try {
      preference = await dataPreferences.getPreferences(context, db_name);
    } catch (err) {
    }
  }

  /**
   * 删除本地存储
   * Deletes the specified Preferences persistence file from memory and removes the Preferences instance.
   */
  async deletePreferences(db_name: string) {
    try {
      await dataPreferences.deletePreferences(context, db_name);
    } catch (err) {
    }
    ;
    preference = preferenceTemp;
  }

  /**
   * Save the data to the Preferences.
   * 持久化存储
   * @param fruit Fruit data.
   */
  async putPreference(data: any, db_name: string, key: string) {
    if (!preference) {
      await this.getPreferencesFromStorage(db_name);
    }
    // The fruit name and fruit quantity data entered by the user are saved to the cached Preference instance.
    try {
      if (typeof data === 'object' && data !== null) {
        await preference.put(key, JSON.stringify(data));
      } else {
        await preference.put(key, data);
      }
    } catch (err) {
    }
    await preference.flush();
  }

  /**
   * 取数据
   * Get preference data.
   */
  async getPreference(db_name: string, key: string) {
    let storage;
    if (!preference) {
      await this.getPreferencesFromStorage(db_name);
    }
    try {
      storage = (await preference.get(key, ''));
    } catch (err) {
    }
    // If the data is empty, a message is displayed indicating that data needs to be written.
    if (!storage) {
      return '';
    }
    return storage;
  }

  writeVpnConnectState(data: any) {
    this.writeData(data, 'vpn_data', 'currentConnect');
  }

  async getVpnConnectState(): Promise<StateModel> {
    let result: string = await this.getData('vpn_data', 'currentConnect');
    if (result) {
      return JSON.parse(result) as StateModel;
    } else {
      return undefined;
    }
  }

  /**
   * write data.
   * 存数据
   * @param fruit  Fruit data.
   */
  writeData(data: any, db_name: string, key: string) {
    // The data is inserted into the preferences database if it is not empty.
    this.putPreference(data, db_name, key);
  }

  /**
   * Process the data obtained from the database.
   */
  async getData(db_name: string, key: string) {
    return await this.getPreference(db_name, key);
  }

  /**
   * Popup window prompt message.
   *
   * @param message Prompt message.
   */
  showToastMessage(message: Resource) {
    promptAction.showToast({
      message: message,
      duration: 3000
    });
  };
}

let preferenceModel = new PreferenceModel();
;

export default preferenceModel;